{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6bYaCABobL5q"
      },
      "source": [
        "##### Copyright 2018 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "FlUw7tSKbtg4"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "08OTcmxgqkc2"
      },
      "source": [
        "# Automatically rewrite TF 1.x and compat.v1 API symbols\n",
        "\n",
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/guide/migrate/upgrade\">\n",
        "    <img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />\n",
        "    View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/migrate/upgrade.ipynb\">\n",
        "    <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n",
        "    Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/upgrade.ipynb\">\n",
        "    <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n",
        "    View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/migrate/upgrade.ipynb\">\n",
        "    <img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />\n",
        "    Download notebook</a>\n",
        "  </td>\n",
        "</table>\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hZSaRPoybOp5"
      },
      "source": [
        "TensorFlow 2.x includes many API changes from TF 1.x and the `tf.compat.v1` APIs, such as reordering arguments, renaming symbols, and changing default values for parameters. Manually performing all of these modifications would be tedious and prone to error. To streamline the changes, and to make your transition to TF 2.x as seamless as possible, the TensorFlow team has created the `tf_upgrade_v2` utility to help transition legacy code to the new API.\n",
        "\n",
        "Note: `tf_upgrade_v2` is installed automatically for TensorFlow 1.13 and later (including all TF 2.x builds).\n",
        "\n",
        "Typical usage is like this:\n",
        "\n",
        "<pre class=\"devsite-terminal devsite-click-to-copy prettyprint lang-bsh\">\n",
        "tf_upgrade_v2 \\\n",
        "  --intree my_project/ \\\n",
        "  --outtree my_project_v2/ \\\n",
        "  --reportfile report.txt\n",
        "</pre>\n",
        "\n",
        "It will accelerate your upgrade process by converting existing TensorFlow 1.x Python scripts to TensorFlow 2.x.\n",
        "\n",
        "The conversion script automates many mechanical API transformations, though many APIs cannot be automatically migrated. It is also not able to fully make your code compatible with TF2 behaviors and APIs. So, it is only a part of your migration journey."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gP9v2vgptdfi"
      },
      "source": [
        "## Compatibility modules\n",
        "\n",
        "Certain API symbols can not be upgraded simply by using a string replacement. Those that cannot be automatically upgraded will be mapped to their locations in the `compat.v1` module. This module replaces TF 1.x symbols like `tf.foo` with the equivalent `tf.compat.v1.foo` reference. If you are already using `compat.v1` APIs by importing TF via `import tensorflow.compat.v1 as tf`, the `tf_upgrade_v2` script will attempt to convert these usages to the non-compat APIs where possible. Note that while some `compat.v1` APIs are compatible with TF2.x behaviors, many are not. Therefore, it's recommended to manually proofread replacements and migrate them to new APIs in the `tf.*` namespace instead of `tf.compat.v1` namespace as quickly as possible.\n",
        "\n",
        "Because of TensorFlow 2.x module deprecations (for example, `tf.flags` and `tf.contrib`), some changes can not be worked around by switching to `compat.v1`. Upgrading this code may require using an additional library (for example, [`absl.flags`](https://github.com/abseil/abseil-py)) or switching to a package in [tensorflow/addons](http://www.github.com/tensorflow/addons).\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s78bbfjkXYb7"
      },
      "source": [
        "## Recommended upgrade process\n",
        "\n",
        "The rest of this guide demonstrates how to use the symbol-rewriting script. While the script is easy to use, it is strongly recommended that you use the script as part of the following process: \n",
        "\n",
        "1. **Unit Test**: Ensure that the code you’re upgrading has a unit test suite with reasonable coverage. This is Python code, so the language won’t protect you from many classes of mistakes. Also ensure that any dependency you have has already been upgraded to be compatible with TensorFlow 2.x.\n",
        "\n",
        "1. **Install TensorFlow 1.15**: Upgrade your TensorFlow to the latest TensorFlow 1.x version, at least 1.15. This includes the final TensorFlow 2.0 API in `tf.compat.v2`.\n",
        "\n",
        "1. **Test With 1.15**: Ensure your unit tests pass at this point. You’ll be running them repeatedly as you upgrade so starting from green is important.\n",
        "\n",
        "1. **Run the upgrade script**: Run `tf_upgrade_v2` on your entire source tree, tests included. This will upgrade your code to a format where it only uses symbols available in TensorFlow 2.0. Deprecated symbols will be accessed with `tf.compat.v1`. These will eventually require manual attention, but not immediately.\n",
        "\n",
        "1. **Run the converted tests with TensorFlow 1.15**: Your code should still run fine in TensorFlow 1.15. Run your unit tests again. Any error in your tests here means there’s a bug in the upgrade script. [Please let us know](https://github.com/tensorflow/tensorflow/issues).\n",
        "\n",
        "1. **Check the upgrade report for warnings and errors**: The script writes a report file that explains any conversions you should double-check, or any manual action you need to take. For example: Any remaining instances of contrib will require manual action to remove. Please consult [the RFC for more instructions](https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md). \n",
        "\n",
        "1. **Install TensorFlow 2.x**: At this point it should be safe to switch to TensorFlow 2.x binaries, even if you are running with legacy behaviors\n",
        "\n",
        "1. **Test with `v1.disable_v2_behavior`**: Re-running your tests with a `v1.disable_v2_behavior()` in the tests' main function should give the same results as running under 1.15.\n",
        "\n",
        "1. **Enable V2 Behavior**: Now that your tests work using the TF2 binaries, you can now begin migrating your code to avoiding `tf.estimator`s and only using supported TF2 behaviors (with no TF2 behavior disabling). See the [Migration guides](https://tensorflow.org/guide/migrate) for details."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6pwSAQEwvscP"
      },
      "source": [
        "## Using the symbol-rewriting `tf_upgrade_v2` script\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "I9NCvDt5GwX4"
      },
      "source": [
        "### Setup\n",
        "\n",
        "Before getting started ensure that TensorFlow 2.x is installed."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DWVYbvi1WCeY"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "\n",
        "print(tf.__version__)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ycy3B5PNGutU"
      },
      "source": [
        "Clone the [tensorflow/models](https://github.com/tensorflow/models) git repository so you have some code to test on:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jyckoWyAZEhZ"
      },
      "outputs": [],
      "source": [
        "!git clone --branch r1.13.0 --depth 1 https://github.com/tensorflow/models"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wfHOhbkgvrKr"
      },
      "source": [
        "### Read the help\n",
        "\n",
        "The script should be installed with TensorFlow. Here is the builtin help:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "m2GF-tlntqTQ"
      },
      "outputs": [],
      "source": [
        "!tf_upgrade_v2 -h"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "se9Leqjm1CZR"
      },
      "source": [
        "### Example TF1 code"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "whD5i36s1SuM"
      },
      "source": [
        "Here is a simple TensorFlow 1.0 script:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mhGbYQ9HwbeU"
      },
      "outputs": [],
      "source": [
        "!head -n 65 models/samples/cookbook/regression/custom_regression.py | tail -n 10"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UGO7xSyL89wX"
      },
      "source": [
        "With TensorFlow 2.x installed it does not run:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TD7fFphX8_qE"
      },
      "outputs": [],
      "source": [
        "!(cd models/samples/cookbook/regression && python custom_regression.py)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iZZHu0H0wLRJ"
      },
      "source": [
        "### Single file\n",
        "\n",
        "The script can be run on a single Python file:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xIBZVEjkqkc5"
      },
      "outputs": [],
      "source": [
        "!tf_upgrade_v2 \\\n",
        "  --infile models/samples/cookbook/regression/custom_regression.py \\\n",
        "  --outfile /tmp/custom_regression_v2.py"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "L9X2lxzqqkc9"
      },
      "source": [
        "The script will print errors if it can not find a fix for the code. "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "r7zpuE1vWSlL"
      },
      "source": [
        "### Directory tree"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2q7Gtuu8SdIC"
      },
      "source": [
        "Typical projects, including this simple example, will use much more than one file. Typically want to update an entire package, so the script can also be run on a directory tree:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XGqcdkAPqkc-"
      },
      "outputs": [],
      "source": [
        "# update the .py files and copy all the other files to the outtree\n",
        "!tf_upgrade_v2 \\\n",
        "    --intree models/samples/cookbook/regression/ \\\n",
        "    --outtree regression_v2/ \\\n",
        "    --reportfile tree_report.txt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2S4j7sqbSowC"
      },
      "source": [
        "Note the one warning about the `dataset.make_one_shot_iterator` function.\n",
        "\n",
        "Now the script works in with TensorFlow 2.x:\n",
        "\n",
        "Note that because the `tf.compat.v1` module is included in TF 1.15, the converted script will also run in TensorFlow 1.15."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vh0cmW3y1tX9"
      },
      "outputs": [],
      "source": [
        "!(cd regression_v2 && python custom_regression.py 2>&1) | tail"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4EgZGGkdqkdC"
      },
      "source": [
        "## Detailed report\n",
        "\n",
        "The script also reports a list of detailed changes. In this example it found one possibly unsafe transformation and included a warning at the top of the file: "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "CtHaZbVaNMGV"
      },
      "outputs": [],
      "source": [
        "!head -n 20 tree_report.txt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1-UIFXP3cFSa"
      },
      "source": [
        "Note again the one warning about the `Dataset.make_one_shot_iterator function`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oxQeYS1TN-jv"
      },
      "source": [
        "In other cases the output will explain the reasoning for non-trivial changes:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WQs9kEvVN9th"
      },
      "outputs": [],
      "source": [
        "%%writefile dropout.py\n",
        "import tensorflow as tf\n",
        "\n",
        "d = tf.nn.dropout(tf.range(10), 0.2)\n",
        "z = tf.zeros_like(d, optimize=False)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7uOkacZsO3XX"
      },
      "outputs": [],
      "source": [
        "!tf_upgrade_v2 \\\n",
        "  --infile dropout.py \\\n",
        "  --outfile dropout_v2.py \\\n",
        "  --reportfile dropout_report.txt > /dev/null"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "m-J82-scPMGl"
      },
      "outputs": [],
      "source": [
        "!cat dropout_report.txt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DOOLN21nTGSS"
      },
      "source": [
        "Here is the modified file contents, note how the script adds argument names to deal with moved and renamed arguments:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "SrYcJk9-TFlU"
      },
      "outputs": [],
      "source": [
        "!cat dropout_v2.py"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wI_sVNp_b4C4"
      },
      "source": [
        "A larger project might contain a few errors. For example convert the deeplab model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "uzuY-bOvYBS7"
      },
      "outputs": [],
      "source": [
        "!tf_upgrade_v2 \\\n",
        "    --intree models/research/deeplab \\\n",
        "    --outtree deeplab_v2 \\\n",
        "    --reportfile deeplab_report.txt > /dev/null"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FLhw3fm8drae"
      },
      "source": [
        "It produced the output files:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4YYLRxWJdSvQ"
      },
      "outputs": [],
      "source": [
        "!ls deeplab_v2"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qtTC-cAZdEBy"
      },
      "source": [
        "But there were errors. The report will help you pin-point what you need to fix before this will run. Here are the first three errors:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UVTNOohlcyVZ"
      },
      "outputs": [],
      "source": [
        "!cat deeplab_report.txt | grep -i models/research/deeplab | grep -i error | head -n 3"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gGBeDaFVRJ5l"
      },
      "source": [
        "## \"Safety\" mode"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BnfCxB7SVtTO"
      },
      "source": [
        "The conversion script also has a less invasive `SAFETY` mode that simply changes the imports to use the `tensorflow.compat.v1` module:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XdaVXCPWQCC5"
      },
      "outputs": [],
      "source": [
        "!cat dropout.py"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "c0tvRJLGRYEb"
      },
      "outputs": [],
      "source": [
        "!tf_upgrade_v2 --mode SAFETY --infile dropout.py --outfile dropout_v2_safe.py > /dev/null"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "91suN2RaRfIV"
      },
      "outputs": [],
      "source": [
        "!cat dropout_v2_safe.py"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EOzTF7xbZqqW"
      },
      "source": [
        "As you can see this doesn't upgrade your code, but does allow TensorFlow 1 code to run against TensorFlow 2 binaries. Note that this does not mean your code is running supported TF 2.x behaviors!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jGfXVApkqkdG"
      },
      "source": [
        "## Caveats\n",
        "\n",
        "- Do not update parts of your code manually before running this script. In particular, functions that have had reordered arguments like `tf.math.argmax` or `tf.batch_to_space` cause the script to incorrectly add keyword arguments that mismap your existing code.\n",
        "\n",
        "- The script assumes that `tensorflow` is imported using `import tensorflow as tf`, or `import tensorflow.compat.v1 as tf`.\n",
        "\n",
        "- This script does not reorder arguments. Instead, the script adds keyword arguments to functions that have their arguments reordered.\n",
        "\n",
        "- Check out [tf2up.ml](https://github.com/lc0/tf2up) for a convenient tool to upgrade Jupyter\n",
        "  notebooks and Python files in a GitHub repository.\n",
        "\n",
        "To report upgrade script bugs or make feature requests, please file an issue on [GitHub](https://github.com/tensorflow/tensorflow/issues)."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "upgrade.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
